package com.server.libs;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.io.File;
import java.io.IOException;

@Configuration

public class Save extends WebMvcConfigurationSupport {
    @Value("${server.host}")
    public String host;

    @Value("${server.file.path}")
    public String path;


    public String toPath(MultipartFile file, String path) throws IOException {
        File saveFile = new File(this.path, path);

        try {
            if (!saveFile.exists()) {
                if (saveFile.mkdirs()) {
                    System.out.println("Directory created successfully");
                } else {
                    throw new IOException("Failed to create directory");
                }
            } else {
                System.out.println("Directory already exists.");
            }
        } catch (IOException e) {
            System.err.println("Error creating directory: " + e.getMessage());
            e.printStackTrace();
        }


        file.transferTo(saveFile);
        return path;
    }

    public String toUrl(MultipartFile file, String path) throws IOException {
        return host + "/image/"+ toPath(file,path);
    }


    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        File file = new File(this.path+"apk/");
        try {
            if (!file.exists()) {
                if (file.mkdirs()) {
                    System.out.println("Directory created successfully");
                } else {
                    throw new IOException("Failed to create directory");
                }
            } else {
                System.out.println("Directory already exists.");
            }
        } catch (IOException e) {
            System.err.println("Error creating directory: " + e.getMessage());
            e.printStackTrace();
        }


        registry.addResourceHandler("/files/**").addResourceLocations("file:"+path);
        registry.addResourceHandler("/image/**").addResourceLocations("file:"+path);
        registry.addResourceHandler("/apk/**").addResourceLocations("file:"+path + "/apk/");
    }
}
